<template>
    <div class="set">
        <div class="test">测试</div>
        <br>
        <div>
            <button @click="doConnected" class="connect">连接</button>
            <button @click="doDisconnected" class="disconnect">断开</button>
        </div>
        <br>
        <div class="set_params">
            <!-- <tr>
                <td>状态：</td>
                <td><input type="number" v-model="publishpowerstate"></td>
            </tr> -->
            <tr>
                <td>门：</td>
                <td><input type="number" v-model="publishdoorswitch"></td>
            </tr>
            <tr>
                <td>温度：</td>
                <td><input type="number" v-model="publishtemp"></td>
            </tr>
            <tr>
                <td>消息：</td>
                <td><input type="text" v-model="publishMessage"></td>
            </tr>
        </div>
        <br>
        <div class="container">
            <button @click="doPublish" class="publish-btn">发布消息</button>
        </div>
        <br>
        <div class="rec_message">
            <p>收到的消息: {{ recvData }}</p>
            <p>收到的params:{{ paramsData }}</p>
        </div>

    </div>
</template>
  
<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import mqtt from 'mqtt';
import { model, rotateDoor, door_isopen } from './blender.js';

const client = ref(null);
const recvData = ref('');
const paramsData = ref('');
const publishpowerstate = ref(null); // 初始化为 null
const publishMessage = ref('');
const publishdoorswitch = ref(null); // 初始化为 null
const publishtemp = ref(null); // 初始化为 null
let reconnectCount = 0;
const publishFlag = ref(false);
const isConnected = ref(false);

const payloadJson = {
    method: "thing.service.property.post",
    id: Date.now().toString(),
    params: {
        DoorSwitch: 0,
        mess: "",
        temp: 0,
    },
    version: "1.0.0",
};

const payloadJson_door = {
    method: "thing.service.property.post",
    id: Date.now().toString(),
    params: {
        DoorSwitch: 0,
    },
    version: "1.0.0",
}

const options = {
    connectTimeout: 10000,
    clientId: 'a1VxoApLdIE.client|securemode=2,signmethod=hmacsha256,timestamp=1718372322863|',
    username: 'client&a1VxoApLdIE',
    password: 'aswsf5774b5d06344d9cb2dfd94dcbe97db6457773e01fee180fbb41fcb920dd',
    cleanSession: false,
    keepAlive: 400,
};

const subscription = {
    topic: '/sys/a1VxoApLdIE/client/thing/service/property/set',
    qos: 0,
};

const publication = {
    topic: '/sys/a1VxoApLdIE/client/thing/event/property/post',
    qos: 0,
};

export const publishDoor = (isOpen) => {
    const { topic, qos } = publication;
    payloadJson_door.params.DoorSwitch = isOpen;
    const payload = JSON.stringify(payloadJson_door);
    client.value.publish(topic, payload, qos, (error) => {
        if (error) {
            console.log('发布失败', error);
        } else {
            console.log('发布成功', payload);
        }
    });
};

export default {
    setup() {

        const doConnected = () => {
            console.log('正在连接...');
            try {
                client.value = mqtt.connect('wss://a1VxoApLdIE.iot-as-mqtt.cn-shanghai.aliyuncs.com:443', options);
            } catch (error) {
                console.log('mqtt连接失败: ', error);
            }
            client.value.on('connect', () => {
                console.log('连接成功');
                if (!isConnected.value) {
                    doSubscribe();
                    isConnected.value = true;
                }
            });

            client.value.on('message', (topic, message) => {
                console.log('收到来自', topic, '的消息', message.toString());
                const messageobject = JSON.parse(message.toString());
                const items = messageobject.items;
                if (items) {
                    paramsData.value = items; // 把 items 赋值给 paramsData
                    recvData.value = message.toString();
                    console.log('提取到的params数据', paramsData);
                    if (paramsData.value.powerstate && paramsData.value.powerstate.value === 1) {
                        rotateDoor(1);

                    } else if (paramsData.value.powerstate && paramsData.value.powerstate.value === 0) {
                        rotateDoor(0);

                    }
                } else {
                    console.error('消息中没有 items 属性');
                }
            });


            client.value.on('error', (error) => {
                console.log('连接出错: ', error);
            });

            client.value.on('reconnect', (error) => {
                console.log(`重新连接... (第 ${++reconnectCount} 次)`, error);
                console.log('当前连接状态:', client.value.connected);
            });
        };

        const doDisconnected = () => {
            try {
                doUnSubscribe();
                client.value.end();
                console.log('断开连接');
            } catch (error) {
                console.log('断开连接失败: ', error.toString());
            }
        };

        const doSubscribe = () => {
            const { topic, qos } = subscription;
            client.value.subscribe(topic, qos, (error) => {
                if (!error) {
                    console.log('订阅成功');
                } else {
                    console.log('订阅失败');
                }
            });
        };

        const doUnSubscribe = () => {
            const { topic } = subscription;
            client.value.unsubscribe(topic, (error) => {
                if (error) {
                    console.log('取消订阅失败', error);
                }
            });
        };


        const doPublish = () => {
            const { topic, qos } = publication;
            payloadJson.params.mess = publishMessage.value;
            payloadJson.params.DoorSwitch = publishdoorswitch.value;
            payloadJson.params.temp = publishtemp.value;
            const payload = JSON.stringify(payloadJson);
            rotateDoor(payloadJson.params.DoorSwitch);//发送消息之后根据DoorSwitch的值控制门的开关
            client.value.publish(topic, payload, qos, (error) => {
                if (error) {
                    console.log('发布失败', error);
                } else {

                    console.log('发布成功', payload);
                }
                // 清除输入内容
                publishMessage.value = '';
                publishdoorswitch.value = null;
                publishtemp.value = null;
            });
        };



        onMounted(() => {
            console.log('组件挂载后执行的代码块');
        });

        onBeforeUnmount(() => {
            console.log('组件销毁前执行的代码块');
            doDisconnected(); // 组件销毁前断开连接
        });

        return {
            doConnected,
            doDisconnected,
            doSubscribe,
            doUnSubscribe,
            doPublish,
            recvData,
            paramsData,
            publishMessage,
            publishpowerstate,
            publishtemp,
            publishFlag,
            publishdoorswitch,
        };
    },
};
</script>
  